package org.example.handler;

import com.alibaba.fastjson.JSONObject;
import org.example.common.enums.ResultEnum;
import org.example.model.dto.UserDetailDTO;
import org.example.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功处理
 */
@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        UserDetailDTO details = (UserDetailDTO) authentication.getDetails();
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("user",details);
        String token = jwtUtils.createToken(null,String.valueOf(details.getUsername()),userMap);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("msg", "Authentication success");
        resMap.put("code", ResultEnum.SuccessResult.getCode());
        resMap.put("token", token);

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSONObject.toJSONString(resMap));
        response.flushBuffer();
    }
}
